﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AMInstantMessaging
{
    public delegate void MainDelegate(Form form, Action action);

    public static class ThreadHelper
    {
        /// <summary>
        /// 在新的线程中运行
        /// </summary>
        /// <param name="action"></param>
        public static void RunInNewThread(Action action)
        {
            new Thread(() => { action(); }).Start();
        }
        
        /// <summary>
        /// 运行在主线程中
        /// </summary>
        /// <param name="form"></param>
        /// <param name="action"></param>
        public static void RunInMainThread(Form form, Action action)
        {
            if (form.InvokeRequired)
            {
                form.Invoke(new MainDelegate(RunInMainThread), new object[] { form, action });
            }
            else
            {
                action();
            }
        }
    }
}
